#rocketmq-python-client==5.0.6

import json
import rocketmq
from rocketmq.client import PushConsumer, ClientConfig, ConsumeFromWhere
from alibabacloud.core.acs_exception import ClientException
from alibabacloud.core.client import AcsClient
from alibabacloud_rocketmq20180626.client import Client as RocketMQ20180626Client
from alibabacloud_rocketmq20180626.models import OnsRegionListRequest, OnsInstanceInServiceListRequest

def get_regions(client):
    request = OnsRegionListRequest()
    response = client.do_action_with_exception(request)
    regions = []
    for region in response.get('Data', []):
        regions.append(region.get('OnsRegionId'))
    return regions

def get_instances(client, region_id):
    request = OnsInstanceInServiceListRequest()
    request.set_RegionId(region_id)
    try:
        response = client.do_action_with_exception(request)
        return response.get('Instances', {}).get('InstanceDo', [])
    except ClientException as e:
        print(f"Error fetching instances for {region_id}: {e}")
        return []

def main(access_key_id, access_key_secret):
    client = RocketMQ20180626Client(
        access_key_id=access_key_id,
        access_key_secret=access_key_secret,
        region_id="cn-hangzhou"  # 默认地域用于调用OnsRegionList
    )

    regions = get_regions(client)
    result = []

    for region in regions:
        instances = get_instances(client, region)
        for instance in instances:
            # 映射属性字段
            attributes = [
                {"attributeName": "实例ID", "attributeValue": instance.get('InstanceId')},
                {"attributeName": "实例名称", "attributeValue": instance.get('InstanceName')},
                {"attributeName": "版本", "attributeValue": "标准版" if instance.get('InstanceType') == 1 else "铂金版"},
                {"attributeName": "状态", "attributeValue": "服务中" if instance.get('InstanceStatus') == 5 else "其他状态"},
                {"attributeName": "创建时间", "attributeValue": instance.get('CreateTime')}
            ]
            # 构造输出格式
            result.append({
                "ciCode": "aliyun_ecs",
                "attributes": attributes
            })

    print(json.dumps(result, ensure_ascii=False, indent=2))

if __name__ == "__main__":
    access_key_id = "YOUR_ACCESS_KEY_ID"
    access_key_secret = "YOUR_ACCESS_KEY_SECRET"
    main(access_key_id, access_key_secret)